const router = require('koa-router')()
const fs = require('fs')
const path = require('path')

//查询全部举报
router.get('/getquestion', async (ctx, next) => {
    let sql = "select * from report order by userid DESC";
    let result = await ctx.db.EXCUTE(sql);
    let image = []
    for (var i = 0; i < result.length; i++) {
        let arr = result[i].image.split('\"');
        for (var j = 0; j < arr.length; j++) {
            if (arr[j].length > 15) {
                let arr1 = arr[j].replace('../../', '')
                let filePath = path.join(__dirname, '../../../小程序/', arr1)
                let fileObj = fs.readFileSync(filePath);
                let file = fileObj.toString('base64');
                let imgUrl = `data:image/png;base64,${file}`
                image.push(imgUrl)
            }
        }
        result[i].image = image
        image = []
    }
    ctx.body = { data: result, status: "获取信息成功" }
})


//搜索举报
router.post('/selquestion', async (ctx, next) => {
    let user = ctx.request.body.user;
    let sql = `select * from report where userId like "%${user}%"`;
    let result = await ctx.db.EXCUTE(sql, [user]);
    if (result.length != 0) {
        let image = []
        for (var i = 0; i < result.length; i++) {
            let arr = result[i].image.split('\"');
            for (var j = 0; j < arr.length; j++) {
                if (arr[j].length > 15) {
                    let arr1 = arr[j].replace('../../', '')
                    let filePath = path.join(__dirname, '../../../小程序/', arr1)
                    let fileObj = fs.readFileSync(filePath);
                    let file = fileObj.toString('base64');
                    let imgUrl = `data:image/png;base64,${file}`
                    image.push(imgUrl)
                }
            }
            result[i].image = image
            image = []
        }
        ctx.body = { code: 200, status: "搜索信息成功", data: result }
    } else {
        ctx.body = { code: 400, status: "输入信息错误,无数据", data: [] }
    }

})

//删除举报
router.post('/delquestion', async (ctx, next) => {
    let id = ctx.request.body.id;
    let delsql = 'delete from report where idreport=?';
    let result = await ctx.db.EXCUTE(delsql, [id]);
    ctx.body = { "code": 200, "msg": "ok", status: "删除成功" };
})

//审核通过
router.post('/sucquestion', async (ctx, next) => {
    let id = ctx.request.body.id;
    let state = ctx.request.body.state;
    let sql = 'update report set state=? where idreport=?';
    let result = await ctx.db.EXCUTE(sql, [state, id]);
    ctx.body = { "code": 200, "msg": "ok", status: "审核通过" };
})

//审核失败
router.post('/passquestion', async (ctx, next) => {
    let id = ctx.request.body.id;
    let state = ctx.request.body.state;
    let sql = 'update report set state=? where idreport=?';
    let result = await ctx.db.EXCUTE(sql, [state, id]);
    ctx.body = { "code": 200, "msg": "ok", status: "审核不通过" };
})

module.exports = router